package com.abner.basis.list;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * ArrayList是线程不安全的,代码示例及解决
 * @Author yuhui
 * @Date: 2024/3/20
 */
public class ArrayListError {

    public static void main(String[] args) {

//        List<Object> list = new ArrayList<>();
        /**
         * 解决list线程不安全的
         *  方案1: Vector(较老不推荐)
         *  方案2: Collections.synchronizedList(较老不推荐)
         *  方案3: CopyOnWriteArrayList(juc包下的)
         */
//        List<Object> list = new Vector<>();
//        List<Object> list = Collections.synchronizedList(new ArrayList<>());
        List<Object> list = new CopyOnWriteArrayList<>();
//        for (int i = 0; i < 20; i++) {
//            new Thread(() -> {
//                list.add(UUID.randomUUID());
//                System.out.println(list);
//            }).start();
//        }

        /**
         * 解决HashSet线程不安全的
         *  CopyOnWriteArraySet(juc包下的)
         */
//        Set<String> set = new CopyOnWriteArraySet<>();
//        for (int i = 0; i < 20; i++) {
//            new Thread(() -> {
//                set.add(UUID.randomUUID().toString());
//                System.out.println(set);
//            }).start();
//        }

        /**
         * 解决HashMap线程不安全的
         *  ConcurrentHashMap(juc包下的)
         */
        Map<String,Object> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                map.put(UUID.randomUUID().toString(),"i");
                System.out.println(map);
            }).start();
        }
    }
}
